<?php

namespace App\Http\Controllers;


use Socialite;
use App\User;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        if (Auth::user()) {
            return redirect('/admin/index');
        }
//        $this->middleware('auth');
    }

    public function redirectToProvider()
    {
        return Socialite::driver('github')->redirect();
    }

    /**
     * 从GitHub获取认证用户信息
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('github')->user();
        if (!User::where('github_id', $user->id)->first()) {
            $userModel = new User;
            $userModel->github_id = $user->id;
            $userModel->email = $user->email;
            $userModel->name = $user->name;
            $userModel->avatar = $user->avatar;
            $userModel->is_show = 1;
            $userModel->save();
            $data['role_id'] = 6;
            $userModel->roles()->sync($data);
        }
        $userInstance = User::where('github_id', $user->id)->firstOrFail();
        Auth::login($userInstance);
        return redirect('/admin/index');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $id = Crypt::decrypt($_GET['caking']);
        $code = Crypt::decrypt($_GET['code']);
        if ($code < time()) {
            return '非常抱歉，您已超时，请重新发送邮件';
        } else {
            $user = User::find($id);
            if ($user->is_show == 0) {
                $data['is_show'] = 1;
                $where['role_id'] = 6;
                $user->update($data);
                $user->roles()->sync($where);
                $html = '<br><p>恭喜您已完成激活，点击下面按钮登陆</p><br><a href="/admin/login" style="text-decoration: none;color:red;">点击登陆</a>';
                return $html;
            } else {
                $html = '<br><p>您已激活成功，不可重新激活</p><br><a href="/admin/login" style="text-decoration: none;color:red;">点击登陆</a>';
                return $html;
            }
        }
    }

    public function mail()
    {
        return view('auth.mail');
    }
}
